package com.he.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.he.entity.Menu;
import com.he.entity.Role;
import com.he.entity.RoleMenu;
import com.he.mapper.RoleMenuMapper;
import com.he.service.MenuService;
import com.he.service.RoleService;
import com.he.mapper.RoleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author hehengjia
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2022-05-10 09:20:15
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService{

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private MenuService menuService;


    @Transactional
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
                //先删除角色所有的绑定关系，再进行重新绑定
                QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("role_id",roleId);
                roleMenuMapper.delete(queryWrapper);
                //之后再增加新的角色与菜单关系
                //CollUtil.newArrayList(menuIds) 拷贝一份新的menuIds把属性赋给menuIdsCopy
                ArrayList<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);
        for (Integer menuId : menuIds) {
                Menu menu = menuService.getById(menuId);
            //说明它是二级菜单,并且传递过来的menuIds里它的没有父级Id
            if (menu.getPid()!=null && !menuIdsCopy.contains(menu.getPid())) {
                //那么我们就得在这加上父级Id
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setMenuId(menuId);
                roleMenu.setRoleId(roleId);
                roleMenuMapper.insert(roleMenu);
        }
    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) {
        return roleMenuMapper.selectByRoleId(roleId);
    }

}




